package com.appspot.moviesessions;

import java.io.FileNotFoundException;
import java.io.InputStream;

import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.View;
import android.widget.TextView;

//todo implement generic view binder
public class MovieListViewBinder implements ViewBinder {

	private ContentResolver contentResolver;
	private UriParser uriParser;
	private BitmapFactory bitmapFactory;

	public MovieListViewBinder(ContentResolver contentResolver,
			UriParser uriParser,
			com.appspot.moviesessions.BitmapFactory bitmapFactory) {
		this.contentResolver = contentResolver;
		this.uriParser = uriParser;
		this.bitmapFactory = bitmapFactory;
	}

	@Override
	public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

		InputStream thumbStream;
		try {
			thumbStream = contentResolver.openInputStream(uriParser
					.parse(cursor.getString(2)));
			// Bitmap bm = BitmapFactory.decodeStream(thumbStream);
			TextView tv = (TextView) view;
			// BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
			Drawable bitmapDrawable = bitmapFactory.bitmapDrawable(thumbStream);
			tv.setCompoundDrawablesWithIntrinsicBounds(bitmapDrawable, null,
					null, null);
			tv.setText(" " + cursor.getString(1));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return true;
	}

}
